package de.earthquake.parser;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import model.Author;
import model.Earthquake;
import model.EarthquakeEntry;
import model.Summary;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class EarthquakeParser {

	private Document dom;

	public Earthquake parseXmlFile(String file) throws ParseException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			dom = db.parse(new File(file));
			return parseDocument();
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (SAXException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return null;
	}

	private Earthquake parseDocument() throws ParseException {
		Earthquake earthquake = new Earthquake();
		Element docEle = dom.getDocumentElement();
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
		
		earthquake.setTitle(getTextValue(docEle, "title"));
		earthquake.setUpdated(format.parse(getTextValue(docEle, "updated")));
		earthquake.setSubtitle(getTextValue(docEle, "subtitle"));
		
		earthquake.setId(getTextValue(docEle, "id"));
		earthquake.setIcon(getTextValue(docEle, "icon"));

		NodeList nl = docEle.getElementsByTagName("author");
		
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {
				Element el = (Element)nl.item(i);
				earthquake.setAuthor(new Author(getTextValue(el, "name")));
			}
		}
		
		nl = docEle.getElementsByTagName("entry");
		
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {
				EarthquakeEntry entry = new EarthquakeEntry();
				Element el = (Element)nl.item(i);
				entry.setId(getTextValue(el, "id"));
				entry.setTitle(getTextValue(el, "title"));
				entry.setUpdated(format.parse(getTextValue(el, "updated")));
				entry.setSummary(new Summary(getTextValue(el, "summary")));
				
				earthquake.addEarthquakeEntry(entry);
			}
		}
		
		return earthquake;
	}
	
	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}


	/**
	 * Calls getTextValue and returns a int value
	 */
	private int getIntValue(Element ele, String tagName) {
		//in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele,tagName));
	}
}
